package com.als.healthymananger.handler;

import com.als.healthymananger.entity.Jurisdiction;
import com.als.healthymananger.entity.JurisdictionGroup;
import com.als.healthymananger.service.JurisdictionGroupService;
import com.als.healthymananger.service.JurisdictionsService;
import com.als.healthymananger.utils.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 权限判定
 * 不同角色拥有不同的权限
 * 不满足权限无法访问该资源
 */
@Slf4j
//@WebFilter(filterName = "jurisdictionFilter", urlPatterns = "/*", initParams = {@WebInitParam(name = "excludedUris", value = "/login/sign-in,/login/sign-up,/login/foget,/util/unauthorized,/util/forbidden")})
//@Order(2)
public class JurisdictionHandler extends OncePerRequestFilter {
//    @Value("${jwt.token-header}")
//    private String tokenHeader;
//    @Value("${jwt.token-head}")
//    private String tokenHead;

    private String tokenHeader = "Authorization";
    private String tokenHead = "Bearer";

//    @Autowired
    private JWTUtil jwtUtil = new JWTUtil();


    @Autowired
    private JurisdictionGroupService jurisdictionGroupService;
    @Autowired
    private JurisdictionsService jurisdictionsService;

    private String excludedUris[];

    @Override
    protected void initFilterBean() throws ServletException {
        // 获取初始化参数
        String excludeUrisParam = this.getFilterConfig().getInitParameter("excludeUrls");

        // 拆分出要排除的过滤路径
        if (StringUtils.isNotBlank(excludeUrisParam))
            this.excludedUris = excludeUrisParam.split(",");
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 是否放行
        boolean flag = false;

        // 当前路径
        String uri = request.getRequestURI();
        log.debug("当前uri: {}", uri);

        if (uri.startsWith("/swagger-ui") || uri.startsWith("/api-doc"))
            flag = true;

        // 排除过滤路径
        for (String excludeUri: excludedUris) {
            if (uri.equals(excludeUri))
                flag = true;
        }

        if (flag)
            filterChain.doFilter(request, response);
        else {
            try{
                // 获取访问类型
                String method = request.getMethod();
                log.debug("访问类型: {}", method);
                // 获取jwt头
                String header = request.getHeader(tokenHeader);
                // 获取jwt
                String jwt = header.substring(tokenHead.length()+1);
                // 获取userType
                String userType = jwtUtil.getClaim(jwt, "userType");

                // 权限验证
                if (userType.equals("mananger"))
                    filterChain.doFilter(request, response);
                else if (userType.equals("master")) {
                    // 获取master的所有权限
                    List<Jurisdiction> jurisdictions = jurisdictionsService.list(new QueryWrapper<Jurisdiction>().last("LEFT JOIN  jurisdiction_group ON  type_name = 'master'"));
                    for (Jurisdiction jurisdiction: jurisdictions) {
                        // 判断请求类型
                        if (method.equals(jurisdiction.getType().toUpperCase())) {
                            // 判断路径
                            if (uri.startsWith(jurisdiction.getName())){
                                flag = true;
                                filterChain.doFilter(request, response);
                            }

                        }
                    }
                    if (flag == false)
                        request.getRequestDispatcher("/util/forbidden").forward(request, response);
                } else if (userType.equals("member")) {
                    // 获取所有权限
                    List<JurisdictionGroup> jurisdictionGroups = jurisdictionGroupService.list(new QueryWrapper<JurisdictionGroup>().eq("type_name", "member"));

                    for (JurisdictionGroup jurisdictionGroup: jurisdictionGroups) {
                        // 获取具体权限
                        Jurisdiction jurisdiction = jurisdictionsService.getById(jurisdictionGroup.getJurisdictionId());
                        // 判断请求类型
                        if (method.equals(jurisdiction.getType().toUpperCase()))
                            // 判断路径
                            if (uri.startsWith(jurisdiction.getName())){
                                flag = true;
                                filterChain.doFilter(request, response);
                            }
                    }
                    if (flag == false)
                        request.getRequestDispatcher("/util/forbidden").forward(request, response);
                }
            } catch (Exception e) {
                request.getRequestDispatcher("/util/forbidden").forward(request, response);
            }
        }
    }
}
